const { get, post } = require('../../../utils/request.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isFirstSet: true,
    focusInput: [false, false, false],
    pwdValue1: ['', '', '', ''],
    pwdValue2: ['', '', '', ''],
    pwdValue3: ['', '', '', ''],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    get('familyconfig/list', {
      'filter_familyUnicode_eq_s': wx.getStorageSync('unicode'),
      'filter_name_eq_s': 'password'
    }, (data) => {
      this.setData({
        isFirstSet: data.length > 0 ? false : true,
        focusInput: data.length > 0 ? [true, false, false] : [false, true, false]
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  cancel() {
    wx.navigateBack();
  },
  submit() {
    const pwd1 = this.data.pwdValue1.join('');
    const pwd2 = this.data.pwdValue2.join('');
    const pwd3 = this.data.pwdValue3.join('');

    if (this.data.isFirstSet) {
      if (pwd2.length < 4 || pwd3.length < 4) {
        wx.showToast({
          title: '请填写密码',
          icon: 'error',
          duration: 2000
        })
        return
      }
    } else {
      if (pwd1.length < 4 || pwd2.length < 4 || pwd3.length < 4) {
        wx.showToast({
          title: '请填写密码',
          icon: 'error',
          duration: 2000
        })
        return
      }
    }

    if (pwd2 != pwd3) {
      wx.showToast({
        title: '输入的密码不一致',
        icon: 'error',
        duration: 2000
      })
      return
    }

    get('familyconfig/password', {
      oldPassword: pwd1,
      password: pwd2
    }, () => {
      wx.showToast({
        title: '成功',
        icon: 'success',
        duration: 2000,
        success: function () {
          setTimeout(() => {
            wx.navigateBack()
          }, 2000);
        }
      })
    })


  },
  inputPassword1({ detail: { value }, currentTarget: { dataset: { index } } }) {
    const defaultValue = ['', '', '', '']
    value.split('').forEach((item, i) => {
      defaultValue[i] = item
    })

    if (index == 0) {
      this.setData({
        pwdValue1: defaultValue
      })
    } else if (index == 1) {
      this.setData({
        pwdValue2: defaultValue
      })
    } else if (index == 2) {
      this.setData({
        pwdValue3: defaultValue
      })
    }
  },

  activeFirstPwdInput({ currentTarget: { dataset: { index } }
  }) {

    const newFocus = this.data.focusInput.map((item, i) => {
      return i == index ? true : false;
    })

    this.setData({
      focusInput: newFocus
    })

  }

})

